package com.wwt.server.config.security;

import com.wwt.server.properties.JwtProperties;
import com.wwt.server.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@Component
@Slf4j

public class JWTAuthenticationTokenFilter extends OncePerRequestFilter {
//    @Resource
    JwtProperties jwtProperties=new JwtProperties();

    private String tokenHeader=jwtProperties.getTokenHeader();
    private String tokenHead=jwtProperties.getTokenHead();
    @Resource
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
//        log.info("################+#{}",tokenHead);
        //取出Token并检验  注意此项目中的Token为BEARER_TOKEN 格式Bearer <token>
//        if(request.getRequestURL().toString().contains("login")){
//            filterChain.doFilter(request,response);
//        }
        String header = request.getHeader(tokenHeader);
//        if (request.getRequestURL().toString().contains("img"))
//            filterChain.doFilter(request,response);
        if (header !=null && header.startsWith(tokenHead)){
            log.info("头部长度：#{}",tokenHead.length());
            String token = header.substring(tokenHead.length());
            String username = JWTUtils.getNameByToken(token);
            //判断用户名是否存在与当前程序空间是否存在用户（即是否登录）
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                //判断用户信息与Token检验
                if (userDetails != null && JWTUtils.validateToken(token,userDetails)){
                    UsernamePasswordAuthenticationToken authenticationToken = new
                            UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                    //将本次请求封装到Details里
                    authenticationToken.setDetails(new
                            WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(request,response);
    }
}